package org.openkoala.mybatisdemo.facade.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.Page;
import org.dayatang.querychannel.QueryChannelService;
import org.openkoala.koalacommons.mybatis.MybatisQueryChannelService;
import org.openkoala.mybatisdemo.application.EmployeeApplication;
import org.openkoala.mybatisdemo.core.domain.Employee;
import org.openkoala.mybatisdemo.facade.EmployeeFacade;
import org.openkoala.mybatisdemo.facade.dto.EmployeeDTO;
import org.openkoala.mybatisdemo.facade.impl.assmebler.EmployeeDtoAssembler;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Named
public class EmployeeFacadeImpl implements EmployeeFacade {

	@Inject
	private EmployeeApplication employeeApplication;

	@Inject
	private MybatisQueryChannelService queryChannel;

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public EmployeeDTO getEmployee(Long id) {
		Employee employee = employeeApplication.getEmployee(id);
		return EmployeeDtoAssembler.EntityToDto(employee);
	}

	public EmployeeDTO saveEmployee(EmployeeDTO employeeDTO) {
		Employee employee = new Employee();
		employee = EmployeeDtoAssembler.DtoToEntity(employeeDTO);
		employeeApplication.saveEmployee(employee);
		employeeDTO.setId((java.lang.Long) employee.getId());
		return employeeDTO;
	}

	public void updateEmployee(EmployeeDTO employeeDTO) {
		Employee employee = Employee.getRepository().get(Employee.class,
				employeeDTO.getId());
		employeeApplication.updateEmployee(EmployeeDtoAssembler
				.DtoToEntity(employeeDTO));
	}

	public void removeEmployee(Long id) {
		employeeApplication.removeEmployee(id);
	}

	public void removeEmployees(Long[] ids) {
		employeeApplication.removeEmployees(ids);
	}

	@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
	public List<EmployeeDTO> findAllEmployee() {
		List<EmployeeDTO> list = new ArrayList<EmployeeDTO>();
		List<Employee> all = Employee.getRepository().findAll(Employee.class);
		for (Employee employee : all) {
			list.add(EmployeeDtoAssembler.EntityToDto(employee));
		}
		return list;
	}

	public Page<Employee> findEmployeeByName(String name, int currentPage,
			int pageSize) {
		Page<Employee> employees = queryChannel
				.createNamedQuery(Employee.class, "findEmployeeByName")
				.addParameter("name", name).setPage(currentPage, pageSize)
				.pagedList();
		return employees;
	}

}
